<?php namespace Phpcmf\Controllers\Admin;

// 邮件群发
class Home extends \Phpcmf\Table
{

    public function __construct(...$params) {
        parent::__construct(...$params);

        \Phpcmf\Service::V()->assign([
            'menu' => \Phpcmf\Service::M('auth')->_admin_menu(
                [
                    '群发记录' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/index', 'fa fa-envelope'],
                    '邮件群发' => [APP_DIR.'/'.\Phpcmf\Service::L('Router')->class.'/add', 'fa fa-plus'],
                    '错误日志' => ['email_log/index', 'fa fa-calendar-o'],
                    '邮件服务器' => ['email/index', 'fa fa-cog'],
                    'help' => [358],
                ]
            ),
        ]);
    }

    // 群发记录
    public function index() {

        $field = [
            'title' => array(
                'ismain' => 1,
                'name' => dr_lang('标题'),
                'fieldname' => 'title',
                'fieldtype' => 'Text',
            ),
            'content' => array(
                'ismain' => 1,
                'name' => dr_lang('内容'),
                'fieldname' => 'content',
                'fieldtype' => 'Text',
            ),
        ];

        $this->_init([
            'table' => 'app_email_log',
            'field' => $field,
            'order_by' => 'inputtime desc',
        ]);

        $this->_List();

        \Phpcmf\Service::V()->assign([
            'field' => $field,
        ]);
        \Phpcmf\Service::V()->display('index.html');
    }

    // 内容查看
    public function content_index() {

        $id = intval($_GET['id']);
        $data = \Phpcmf\Service::M()->table('app_email_log')->get($id);

        echo $data['content'];exit;

    }

    // 删除群发
    public function del() {
        $this->_init([
            'table' => 'app_email_log',
        ]);
        $this->name = dr_lang('邮件群发记录');
        $this->_Del(
            \Phpcmf\Service::L('Input')->get_post_ids(),
            null,
            null,
            \Phpcmf\Service::M()->dbprefix('app_email_log')
        );
    }

    // 发送邮件
    public function add() {

        $field = array(
            'content' => array(
                'ismain' => 1,
                'name' => dr_lang('邮件内容'),
                'fieldtype' => 'Ueditor',
                'fieldname' => 'content',
                'setting' => array(
                    'option' => array(
                        'mode' => 1,
                        'height' => 300,
                        'required' => 1,
                        'width' => '100%'
                    ),
                )
            ),
        );

        $type = [
            0 => dr_lang('全部'),
            1 => dr_lang('单个'),
            2 => dr_lang('批量'),
        ];
        foreach ($this->member_cache['group'] as $id => $t) {
            $type['g'.$id] = $t['name'];
        }

        \Phpcmf\Service::V()->assign([
            'type' => $type,
            'form' => dr_form_hidden(),
            'smtp' => \Phpcmf\Service::M()->table('mail_smtp')->getAll(),
            'myfield' => dr_fieldform($field['content'], '', 0),
        ]);
        \Phpcmf\Service::V()->display('send.html');
    }


    // 内容处理
    public function todo_add() {

        $post = \Phpcmf\Service::L('Input')->post('data');
        $cache = [];

        switch ($post['type']) {

            case '0':
                // 全部会员
                $data = \Phpcmf\Service::M()->table('member')->getAll();
                if ($data) {
                    foreach ($data as $t) {
                        $t['email'] && $cache[] = $t['email'];
                    }
                }
                break;

            case '1':
                //单个
                $post['email'] && $cache[] = $post['email'];
                break;

            case '2':
                //批量
                $data = explode(PHP_EOL, $post['emails']);
                if ($data) {
                    foreach ($data as $t) {
                        $t && $cache[] = $t;
                    }
                }
                break;

            default:
                // 用户组
                $gid = (int)substr($post['type'], 1);
                $data = \Phpcmf\Service::M()->query_sql('select `email` from `{dbprefix}member` where `id` in (select `uid` from `{dbprefix}member_group_index` where `gid`='.$gid.' )', 1);
                if ($data) {
                    foreach ($data as $t) {
                        $t['email'] && $cache[] = $t['email'];
                    }
                }
                break;

        }

        $cache && $cache = array_unique($cache);

        !count($cache) && $this->_json(0, dr_lang('无可用邮箱'));
        !$post['title'] && $this->_json(0, dr_lang('主题不存在'));
        !$post['content'] && $this->_json(0, dr_lang('内容不存在'));

        $rt = \Phpcmf\Service::M()->table('app_email_log')->insert([
            'uid' => $this->uid,
            'username' => $this->admin['username'],
            'title' => $post['title'],
            'content' => $post['content'],
            'counts' => count($cache),
            'errors' => 0,
            'inputtime' => SYS_TIME,
        ]);
        !$rt['code'] && $this->_json(0, $rt['msg']);

        // 存储文件
        \Phpcmf\Service::L('cache')->set_data('app-email-send', [
            'id' => $rt['code'],
            'smtp' => $post['smtp'],
            'emails' => dr_save_bfb_data($cache),
            'title' => $post['title'],
            'content' => $post['content'],
        ], 3600);

        $this->_json(1, 'ok', ['url' => dr_url('email/home/show_index', ['counts'=> count($cache)])]);
    }


    // 内容处理
    public function show_index() {
        \Phpcmf\Service::V()->assign([
            'menu' => '',
            'hidebtn' => 1,
            'todo_url' =>  dr_url('email/home/send_add'),
            'count_url' =>  dr_url('email/home/show_count_index'),
        ]);
        \Phpcmf\Service::V()->display('bfb.html');exit;
    }

    // 内容数量统计
    public function show_count_index() {

        $data = \Phpcmf\Service::L('cache')->get_data('app-email-send');
        !count($data) && $this->_json(0, dr_lang('无可用邮箱'));

        $this->_json(count($data['emails']), 'ok');
    }

    public function send_add() {

        $page = max(1, intval($_GET['pp']));
        $cache = \Phpcmf\Service::L('cache')->get_data('app-email-send');
        !$cache && $this->_json(0, dr_lang('邮件地址缓存不存在'));
        !$cache['id'] && $this->_json(0, dr_lang('邮件记录id不存在'));

        $data = $cache['emails'][$page];
        if ($data) {
            $html = '';
            foreach ($data as $email) {
                if ($cache['smtp']) {
                    $smtp = \Phpcmf\Service::L('cache')->get('email');
                    $dmail = \Phpcmf\Service::L('email');
                    $ck = $smtp[$cache['smtp']];
                    if (!$ck) {
                        $$this->_json(0, dr_lang('没有可用的邮箱'));
                    }
                    $config = array(
                        'host' => $ck['host'],
                        'user' => $ck['user'],
                        'pass' => $ck['pass'],
                        'port' => $ck['port'],
                        'from' => $ck['user']
                    );
                    $code = $dmail->set($config)->send($email, $cache['title'], $cache['content']);
                    if ($code) {
                        $rt = dr_return_data(1, 'ok');
                    } else {
                        $rt = dr_return_data(0, $dmail->error);
                    }
                } else {
                    // 随机
                    $rt = \Phpcmf\Service::M('member')->sendmail($email, $cache['title'], $cache['content']);
                }
                if (!$rt['code']) {
                    $ok = "<span class='error'>".$rt['msg']."</span>";
                    $class = ' p_error';
                    \Phpcmf\Service::M()->db->table('app_email_log')->where('id', intval($cache['id']))->increment('errors', 1);
                } else {
                    $ok = "<span class='ok'>".dr_lang('发送成功')."</span>";
                }
                $html.= '<p class="'.$class.'"><label class="rleft">'.$email.'</label><label class="rright">'.$ok.'</label></p>';

            }
            $this->_json($page + 1, $html);
        }

        // 完成
        \Phpcmf\Service::L('cache')->init()->delete('app-email-send');
        $this->_json(100, '');
    }

}
